import 'package:star_author/config/app.dart';
import 'package:star_author/controller/app_package_info_getx_controller.dart';
import 'package:star_author/provider/index.dart';
import 'package:star_author/route/route_util.dart';
import 'package:star_author/utils/common_util/log_util.dart';
import 'package:star_author/utils/http/http_util.dart';
import 'package:star_author/utils/rong_im/rong_im.dart';
import 'package:star_author/utils/toast_util.dart';
import 'package:star_author/utils/utils.dart';
import 'package:star_author/views/login/phone_login.dart';
import 'package:star_author/views/stream/overlay_video.dart';
import 'package:dio/dio.dart';
import 'package:dio_log/interceptor/dio_log_interceptor.dart';
import 'package:fk_user_agent/fk_user_agent.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart' as getX;
import 'package:get/get.dart';
import 'package:package_info/package_info.dart';
import 'package:provider/provider.dart';

import 'base_configuration.dart';

class API {
  static BaseOptions _options = BaseOptions(
    baseUrl: '${HttpUtil.getServerPath()}/api/v1',
    connectTimeout: 60 * 1000,
    receiveTimeout: 60 * 1000,
    sendTimeout: 60 * 1000,
  );

  static Dio _dio = Dio(_options)
    ..interceptors.add(LogInterceptor(
        requestBody: true,
        responseBody: true,
        logPrint: (e) {
          LogUtil.v(e);
        }))
    ..interceptors.add(DioLogInterceptor())
    ..interceptors.add(
      InterceptorsWrapper(
        onRequest: (options, handler) {
          BuildContext? context = App.materialKey.currentContext;
          LogUtil.v("请求时间:${DateTime.now()}");
          //需要重新设置一遍 不然拿到的地址是没有切换环境的地址 ，请求会有问题
          resetDio();
          checkNetwork();
          var user =
              Provider.of<UserProvider>(context as BuildContext, listen: false);
          if (user.token != null)
            options.headers['X-Authorization'] = user.token;

          PackageInfo? packageInfo =
              Get.find<AppPackageInfoGetXController>().packageInfo;
          String version = packageInfo?.version ?? "";
          options.headers['X-APP-VERSION'] = version;
          options.headers['X-ORIGINAL-UA'] = FkUserAgent.webViewUserAgent ?? '';

          LogUtil.v("options.headers${options.headers}");
          return handler.next(options); //continue
        },
        onResponse: (response, handler) {
          String xRuntimeHeader = response.headers['x-runtime']?[0] ?? "";
          LogUtil.v("接口响应时间:$xRuntimeHeader");
          return handler.next(response); // continue
        },
        onError: (DioError e, handler) {
          try {
            int? code = e.response?.statusCode;
            BuildContext? context = App.materialKey.currentContext;
            final msg = e.response?.data['msg'];
            // 超时
            if (e.type == DioErrorType.connectTimeout ||
                e.type == DioErrorType.receiveTimeout) {
              ToastUtil.show("连接超时，请切换网络重试");
              EasyLoading.dismiss();
            } else if (code == 500) {
              ToastUtil.show("当前无法连接正常，请联系客服");
              EasyLoading.dismiss();
            } else {
              if (code == 401) {
                EasyLoading.dismiss();
                OverlayVideo.hidden();
                List noShowDialogList = [
                  'product_detail',
                  '/GoodDetailPage',
                  "/Bank",
                  "/AliPay",
                  "notification-newest",
                  "/BidderHome",
                  "/ReturnBond",
                ]; // 不需要弹框
                List code = ["/Bank", "/AliPay"]; //验证码输入
                //出价页面 已经结拍后去出价不需要弹框

                if (noShowDialogList.contains(getX.Get.currentRoute)) {
                  //评估和商品详情 不需要弹框
                } else if (code.contains(getX.Get.currentRoute)) {
                  if (e.requestOptions.path != "/withdraws/" &&
                      e.requestOptions.method == "POST") {
                    //提现接口不需要报错
                    EasyLoading.showToast(msg.toString());
                  }
                } else {
                  EasyLoading.showToast(msg.toString());
                  if (![PhoneLoginPage.routeName]
                      .contains(getX.Get.currentRoute)) {
                    UserProvider user =
                        Provider.of<UserProvider>(context!, listen: false);
                    user.clearToken();
                    RongUtil.disconnect();
                    RouteUtil.onVerifyLogin();
                  }
                  // final expired = e.response?.data['expired'] ?? false;
                  // Alert.showLoginTip(msg, context as BuildContext, clearToken: expired);
                }
              } else if (code == 400) {
              } else if (e.requestOptions.path != "/tenders/" &&
                  e.requestOptions.method == "POST" &&
                  code == 422) {
              } else {
                EasyLoading.dismiss();
                if (msg != null) {
                  if (e.requestOptions.path.indexOf('logistic') == -1) {
                    EasyLoading.showToast(msg.toString());
                  }
                }
              }
            }
          } catch (e) {
            LogUtil.v(e.toString());
          }
          return handler.next(e); //continue
          // If you want to resolve the request with some custom data，
          // you can resolve a `Response` object eg: `handler.resolve(response)`.
        },
      ),
    );

  //重置一下dio的请求地址
  static resetDio() {
    _dio.options.baseUrl = HttpUtil.getServerPath() + "/api/v1";
  }

  static Future normalLogin(String mobile, String code) {
    return _dio
        .post('/sessions/normal', data: {'mobile': mobile, 'code': code});
  }

  static Future wechatLogin(String code) {
    return _dio.post('/sessions/wechat_app', data: {'code': code});
  }

  static Future getBackflows(Map<String, dynamic> data) {
    return _dio.get('/backflows', queryParameters: data);
  }

  //search_home
  static Future getHomepageSearch(Map<String, dynamic> data) {
    return _dio.get('/backflows/homepage_search', queryParameters: data);
  }

  static Future getStudiosBackflows(Map<String, dynamic> data) {
    return _dio.get('/studios/${StreamConf.liveId}/backflows',
        queryParameters: data);
  }

  static Future getHarvest(Map<String, dynamic> data) {
    return _dio.get('/harvest', queryParameters: data);
  }

  //https://dev.huiliu.net/api/v1/app_update_log
  static Future getAppVersion() {
    return _dio.get(
      '/app_update_log',
    );
  }

  static Future getSettings() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    //版本名
    String version = packageInfo.version;
    return _dio.get(
      '/settings?app_version=' + version,
    );
  }

  static Future vocabularies_categories(categoryId, {target}) {
    return _dio.get('/vocabularies_categories',
        queryParameters: {"category_id": categoryId, "target": target});
  }

  static Future createBackflow(payload) {
    return _dio.post('/backflows', data: payload);
  }

  static Future createTreasure(payload) {
    return _dio.post('/treasures', data: payload);
  }

  //刚刚出价
  static Future getRecentTenders(count) {
    return _dio.get('/recent_tenders?count=${count}');
  }

  static Future generateBackflow(id) {
    return _dio.put('/treasures/${id}/generate_backflow');
  }

  //我要评价
  static Future rating(id, data) {
    return _dio.post('/backflows/${id}/rating', data: data);
  }

  //物流信息/api/v1/backflows/{id}/logistic
  static Future backflowsLogistic(id) {
    return _dio.get('/backflows/${id}/logistic');
  }

  //选择退货
  static Future afterSalePreview(ids) {
    return _dio
        .post('/after_sale_services/preview', data: {"line_item_ids": ids});
  }

  static Future createAssessment(payload) {
    return _dio.post('/assessments', data: payload);
  }

  static Future rejectTreasure(id, reason) {
    return _dio.put('/treasures/${id}/reject', data: reason);
  }

  static Future createTender(payload) {
    return _dio.post('/tenders', data: payload);
  }

  static Future getBackflowDetail(id) {
    return _dio.get('/backflows/$id');
  }

  static Future getMyBackflowDetail(id) {
    return _dio.get('/backflows/$id/order');
  }

  static Future clearTrack() {
    return _dio.put('/tracks/clear');
  }

  static Future getMyTracks() {
    return _dio.get('/tracks');
  }

  static Future getTenders(id) {
    return _dio.get('/tenders', queryParameters: {'backflow_id': id});
  }

  static Future getRelate(data) {
    return _dio.get('/backflows/related', queryParameters: data);
  }

  static Future setBackflowStar(id) {
    return _dio.post('/backflows/${id}/star');
  }

  static Future delBackflowStar(id) {
    return _dio.delete('/backflows/${id}/star');
  }

  static Future createBidder(payload) {
    return _dio.post('/bidders', data: payload);
  }

  static Future updateBidder(payload) {
    return _dio.put('/bidders', data: payload);
  }

  static Future getUserInfo() {
    return _dio.get('/current', queryParameters: {
      "scene": "happ-${Get.currentRoute}",
    });
  }

  static Future getBanners() {
    return _dio.get('/banners');
  }

  static Future updateUserInfo(payload) {
    return _dio.put('/current', data: payload);
  }

  static Future getMyBackflows(Map<String, dynamic> data) {
    return _dio.get('/backflows/present', queryParameters: data);
  }

  static Future getTreasures(data) {
    return _dio.get('/treasures', queryParameters: data);
  }

  static Future getMyTreasures(data) {
    return _dio.get('/treasures/current', queryParameters: data);
  }

  static Future getStaredBackflows(data) {
    return _dio.get('/backflows/stared', queryParameters: data);
  }

  static Future getTreasuresHistories(Map<String, dynamic> data) {
    return _dio.get('/treasures/histories', queryParameters: data);
  }

  static Future getTreasure(id) {
    return _dio.get('/treasures/${id}');
  }

  static Future getTreasureReport(id) {
    return _dio.get('/treasures/${id}/report');
  }

  static Future getMyTenders(Map<String, dynamic> data) {
    return _dio.get('/tenders/present', queryParameters: data);
  }

  static Future getTenderHistories(Map<String, dynamic> data) {
    return _dio.get('/tender_histories/present', queryParameters: data);
  }

  static Future getNewestNotifications() {
    return _dio.get('/notifications/newest');
  }

  static Future clearNotifications() {
    return _dio.put('/notifications/clear');
  }

  static Future getNotifications(Map<String, dynamic> data) {
    return _dio.get('/notifications', queryParameters: data);
  }

  static Future delBackflow(id) {
    return _dio.put('/backflows/$id/remove');
  }

  ///api/v1/orders/{id}/paid_checking 判断是否支付
  static Future paidChecking(id) {
    return _dio.get(
      '/orders/${id}/paid_checking',
    );
  }

  //保证金是否支付/api/v1/earnest_money/{id}/paid_checking
  static Future EarnestMoneyPaidChecking(id) {
    return _dio.get(
      '/earnest_money/${id}/paid_checking',
    );
  }

  //获取证书费用相关信息--是否支付
  static Future backOrders(id) {
    return _dio.get(
      '/back_orders/${id}',
    );
  }

  //支付接口-alipay--订单
  static Future toAdapayOrder(id, type) {
    return _dio.post('/orders/$id/adapay?channel_type=$type');
  }

  //支付接口/api/v1/orders/{order_id}/shipment_certificate_fees/adapay
  static Future toAdapayShipmentCertificateFees(id, data) {
    return _dio.post('/orders/$id/shipment_certificate_fees/adapay',
        data: data);
  }

  //支付接口-alipay--保证金
  static Future toAdapayEarnestMoney(
    id,
    type,
  ) {
    return _dio.post('/earnest_money/${id}/adapay?channel_type=$type');
  }

  //收到货品
  static Future closeCompletely(id) {
    return _dio.put('/backflows/${id}/close_completely');
  }

  static Future priceAdjustment(id, data) {
    return _dio.put('/backflows/${id}/price_adjustment', data: data);
  }

  static Future rebackflow(id) {
    return _dio.put('/backflows/${id}/again');
  }

  static Future confirmImmediate(id) {
    return _dio.put('/backflows/${id}/confirm_with_returned_immediately');
  }

  static Future backflowShip(data) {
    return _dio.put('/backflows/batch_ship', data: data);
  }

  static Future backflowStore(data) {
    return _dio.put('/backflows/batch_store', data: data);
  }

  static Future getLogistic(id) {
    return _dio.get('/backflows/${id}/logistic');
  }

  //修改地址
  static Future updateAddress(id, map) {
    return _dio.put('/address_book/${id}', data: map);
  }

  //删除
  static Future deleteAddress(id) {
    return _dio.delete(
      '/address_book/${id}',
    );
  }

  //获取地址
  static Future getAddress(id) {
    return _dio.get(
      '/address_book/${id}',
    );
  }

  //地址解析
  static Future addressCorrect(address) {
    return _dio.get('/address_book/address_correct/', queryParameters: address);
  }

  //获取地址集合
  static Future getAddressList() {
    return _dio.get(
      '/address_book',
    );
  }

  //创建地址
  static Future createAddress(data) {
    return _dio.post('/address_book', data: data);
  }

  ///api/v1/feedback
  //用户提交意见反馈
  static Future feedback(data) {
    return _dio.post('/feedback', data: data);
  }

  //购物车列表
  static Future shoppingCart() {
    return _dio.get('/shopping_cart');
  }

  ///添加购物车
  static Future addShoppingCart(data) {
    return _dio.post('/shopping_cart', data: data);
  }

  //商品移入收藏列表
  static Future batchStar(id) {
    return _dio.put('/shopping_cart/batch_star', data: {"backflow_ids": id});
  }

  //删除商品
  static Future shoppingCartRemove(id) {
    return _dio.put('/shopping_cart/remove', data: {"backflow_ids": id});
  }

  //删除全部
  static Future shoppingCartClear() {
    return _dio.put('/shopping_cart/clear');
  }

  //实名认证
  static Future apply(data) {
    return _dio.post("/identifications/apply", data: data);
  }

  //创建订单
  static Future createOrders(data) {
    return _dio.post("/orders", data: data);
  }

  //我的订单
  static Future present(data) {
    return _dio.get('/orders/present', queryParameters: data);
  }

  //取消订单
  static Future closeOrder(id) {
    return _dio.put('/orders/$id/close');
  }

  //删除订单
  static Future removeOrder(id) {
    return _dio.put('/orders/$id/remove');
  }

  ///售后列表
  static Future afterSaleServices(data) {
    return _dio.get('/after_sale_services');
  }

  ///用户信息
  static Future account() {
    return _dio.get('/account');
  }

  ///用户信息
  static Future particulars(data) {
    return _dio.get('/particulars', queryParameters: data);
  }

  ///提现详情
  static Future withdrawsInfo(id) {
    return _dio.get('/withdraws/${id}');
  }

  static Future withdrawsInfoEvents(id) {
    return _dio.get('/withdraws/${id}/events');
  }

  //获取物流信息
  static Future logistic(id) {
    return _dio.get('/orders/$id/logistic');
  }

  //获取物流信息---售后/api/v1/after_sale_services/{id}/logistic
  static Future afterSaleServiceslogistic(id) {
    return _dio.get('/after_sale_services/$id/logistic');
  }

  //确认收货 --订单/api/v1/orders/{id}/confirm
  static Future confirmOrder(id) {
    return _dio.put('/orders/$id/confirm');
  }

  //app支付/api/v1/orders/{id}/app_pay
  static Future appPay(id, [type = 'wechat']) {
    return _dio.put('/orders/$id/app_pay?pay_type=$type');
  }

  //取消售后/api/v1/after_sale_services/{id}/close
  static Future afterSaleServicesClose(id) {
    return _dio.put('/after_sale_services/$id/close');
  }

  //获取订单详情
  static Future getOrderInfo(id) {
    return _dio.get('/orders/$id');
  }

  ///api/v1/earnest_money/{id}/app_pay  支付保证金
  static Future earnestMoney(id, [type = 'wechat']) {
    return _dio.put('/earnest_money/$id/app_pay?pay_type=$type');
  }

  ///api/v1/earnest_money 创建保证金单
  static Future createEarnestMoney(data) {
    return _dio.post('/earnest_money', data: data);
  }

  //修改订单地址/api/v1/orders/{id}/address
  static Future updateOrderAddress(id, addressId) {
    return _dio
        .put('/orders/$id/address', queryParameters: {"address_id": addressId});
  }

  //创建售后
  static Future createAfterSaleServices(data) {
    return _dio.post('/after_sale_services', data: data);
  }

  //售后详情
  static Future afterSaleServicesDetail(id) {
    return _dio.get('/after_sale_services/${id}');
  }

  //取消售后/api/v1/after_sale_services/{id}/close
  static Future cancelAfterSaleService(id) {
    return _dio.put('/after_sale_services/${id}/close');
  }

  //填写退货物流信息/api/v1/after_sale_services/{id}/ship
  static Future ship(id, data) {
    return _dio.put('/after_sale_services/${id}/ship', data: data);
  }

  //售后--收货/api/v1/after_sale_services/{id}/store
  static Future store(id, code) {
    return _dio.put('/after_sale_services/${id}/store', data: {"code": code});
  }

  //删除售后订单/api/v1/after_sale_services/{id}/remove
  static Future removeAfterSale(id) {
    return _dio.put('/after_sale_services/${id}/remove');
  }

  //提前结拍/api/v1/backflows/{id}/stop_competitive_in_advance
  static Future stopCompetitiveInAdvance(id) {
    return _dio.put('/backflows/${id}/stop_competitive_in_advance');
  }

  //重新${App.evaluation_text}/api/v1/backflows/{id}/evaluate_again
  static Future evaluateAgain(id) {
    return _dio.put(
      '/backflows/${id}/evaluate_again',
    );
  }

  //获取等级信息/api/v1/level_references
  static Future getLevels(String level_type) {
    return _dio
        .get('/level_references/', queryParameters: {"level_type": level_type});
  }

  ///api/v1/guarantee_refunds 退回保证金
  static Future guaranteeRefunds(price, password) {
    return _dio.post('/guarantee_refunds/',
        data: {"price": price, "password": password});
  }

  ///api/v1/guarantee_refunds 保证金提现
  static Future getGuaranteeRefunds(data) {
    return _dio.get('/guarantee_records/', queryParameters: data);
  }

  ///api/v1/bankcards 添加银行卡
  static Future bankcards(data) {
    return _dio.post('/bankcards/', data: data);
  }

  //获取银行卡列表
  static Future getBankcards() {
    return _dio.get(
      '/bankcards/',
    );
  }

  //发送验证码---提现 /api/v1/password/reset_and_send
  static Future resetAandSend() {
    return _dio.post(
      '/password/reset_and_send',
    );
  }

  ///api/v1/bankcards/{id} 删除银行卡
  static Future deleteBankcards(id) {
    return _dio.delete(
      '/bankcards/$id',
    );
  }

  ///api/v1/{type}/binding 绑定微信
  static Future bindingWeChat(data) {
    return _dio.put('/wechat/binding_app', data: data);
  }

  ///api/v1/{type}/binding 绑定手机号
  static Future bindingMobile(data) {
    return _dio.put('/mobile/binding_app', data: data);
  }

  ////api/v1/withdraws 提现申请
  static Future withdraws(data) {
    return _dio.post('/withdraws/', data: data);
  }

  //取回货品的取货码/api/v1/backflows/batch_attach_back_code
  static Future batchAttachBackCode(id, [ids]) {
    return _dio.put('/backflows/batch_attach_back_code', data: {
      "ids": ids ?? [id]
    });
  }

  //取回货品的取货码
  static Future orderBatchAttachBackCode(id, [ids]) {
    return _dio.put('/orders/batch_attach_back_code', data: {
      "ids": ids ?? [id]
    });
  }

  //取消回流的寄回地址/api/v1/backflows/batch_attach_back_address
  static Future batchAttachBackAddress(id, addressId, [ids, delivery = true]) {
    return _dio.put('/backflows/batch_attach_back_address', data: {
      "ids": ids ?? [id],
      "address_id": addressId,
      "back_cash_on_delivery": delivery,
    });
  }

  //取货的时候可以对中拍订单追加取货地址，这里传订单id列表
  static Future ordersBatchAttachBackAddress(id, addressId,
      [ids, delivery = true, Map<String, dynamic> map = const {}]) {
    return _dio.put('/orders/batch_attach_back_address', data: {
      "ids": ids ?? [id],
      "address_id": addressId,
      "back_cash_on_delivery": delivery,
      ...map
    });
  }

  //证书费用--支付参数
  static Future backOrdersAdapayToPay(id, type) {
    return _dio.post(
      '/back_orders/${id}/adapay?channel_type=$type',
    );
  }

  //证书费用--支付参数
  static Future to_pay_logistic_insurances(id, type) {
    return HttpUtil.commonRequest(
      Get.context!,
      '/api/v1/logistic_insurances/$id/adapay?channel_type=$type',
      method: HttpUtil.MethodPost,
    );
  }

  // 获取我的中拍订单列表
  static Future getMyTenderOrders(data) {
    return _dio.get('/orders/winning_present', queryParameters: data);
  }

  // 委托寄售
  //线下寄售
  static Future ordersBatchSaleOffline(data) {
    return _dio.put('/orders/batch_sale_offline', data: data);
  }

  static Future batchCloseBackflows(data) {
    return _dio.put('/backflows/batch_close', data: data);
  }

  static Future getTenderOrderDetail(int id) {
    return _dio.get('/orders/$id/winning');
  }

  static Future getTenderBackLogistic(int id) {
    return _dio.get('/backflows/$id/back_logistic');
  }

  static Future changeOrderAddress(int id, data) {
    return _dio.put('/orders/$id/address', data: data);
  }

  static Future changeBackflowAddress(int id, data) {
    return _dio.put('/backflows/$id/back_address', data: data);
  }

  static Future changeOrderBackflowAddress(int id, data) {
    return _dio.put('/orders/$id/back_address', data: data);
  }

  //推荐人佣金
  static Future performance() {
    return _dio.get('/referrers/performance');
  }

  //推荐人所有佣金
  static Future performances(data) {
    return _dio.get('/referrers/performances', queryParameters: data);
  }

  //推荐客户
  static Future users(data) {
    return _dio.get('/referrers/users', queryParameters: data);
  }

  //直播模块
  static Future getChannelList() {
    return _dio.get('/studios');
  }

  static Future getRTMToken(data) {
    return _dio.post('/obtain_agora_rtm_token', data: data);
  }

  static Future getRTCToken(data) {
    return _dio.post('/obtain_agora_rtc_token', data: data);
  }

  //开播
  static Future open(id) {
    return _dio.post(
      '/studios/${id}/open',
    );
  }

  static Future join(id) {
    return _dio.post(
      '/studios/${id}/join',
    );
  }

  static Future checkIfExists(id) {
    return _dio.get(
      '/studios/${id}/check_if_exists',
    );
  }

  static Future leave(id) {
    return _dio.post(
      '/studios/${id}/leave',
    );
  }

  static Future close(id) {
    return _dio.post(
      '/studios/${id}/close',
    );
  }

  static Future getLiveInfo(id) {
    return _dio.get(
      '/studios/${id}',
    );
  }

  //直播间发言
  static Future sendWords(id, words) {
    return _dio.post('/studios/${id}/send_words', data: {"words": words});
  }

  //直播间禁止发言
  static Future banUser(id) {
    return _dio.post('/studios/${id}/ban_user');
  }

  //直播间解禁发言
  static Future unBanUser(id) {
    return _dio.post('/studios/${id}/unban_user');
  }

  //直播间删除用户发言
  static Future removeWords(id) {
    return _dio.post('/studios/${id}/remove_words');
  }

  //获取上传地址
  static Future upload_directly_meta_information(queryParameters) {
    return _dio.post('/upload_directly_meta_information',
        queryParameters: queryParameters);
  }

  //绑定视频
  static Future attach_recording_video(id, recording_video, anchor_id) {
    return _dio
        .put('/backflows/${id}/attach_recording_video', queryParameters: {
      "recording_video": recording_video,
      "anchor_id": anchor_id,
    });
  }
}
